<template>
  <el-dialog
    title="选择商品"
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="handleClose"
    class="product-selector-dialog"
  >
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select
            v-model="searchForm.category_id"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品列表 -->
    <el-table
      :data="productList"
      v-loading="loading"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="productTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="商品图片" width="120">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.main_image"
            :preview-src-list="[scope.row.main_image]"
            style="width: 80px; height: 80px"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="120">
        <template slot-scope="scope">
          <div class="product-info">
            <div class="product-name">{{ scope.row.name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="limit_quantity" label="限购(拼团和秒杀不要选择限购商品)" width="300">
          <template slot-scope="scope">
            <div style="color:red" v-if="scope.row.limit_quantity">
              {{ `限购${scope.row.limit_quantity}件`  }}
            </div>
            <div v-else>
              不限购
            </div>
            <!-- <el-input-number disabled v-model="scope.row.stock" :min="0" size="mini"></el-input-number> -->
          </template>
        </el-table-column>
      <el-table-column prop="category_id" label="分类" width="100">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.category_id) }}
        </template>
      </el-table-column>
      <el-table-column label="价格信息" width="200">
        <template slot-scope="scope">
          <div class="price-info" v-if="scope.row.sku">
            <div class="current-price">¥{{ scope.row.sku.price }}</div>
            <div class="vip-price">秒杀价: ¥{{ scope.row.sku.vip_price }}</div>
            <div class="market-price">市场价: ¥{{ scope.row.sku.market_price }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="160" />
    </el-table>

    <!-- 过滤统计信息 -->
    <div v-if="productType !== 'all' && filterStats.hiddenCount > 0" class="filter-stats">
      <el-alert
        :title="`当前页面过滤了 ${filterStats.hiddenCount} 个不符合条件的商品`"
        type="info"
        :closable="false"
        show-icon
      >
        <template slot="default">
          <div class="stats-detail">
            <span>本页获取: {{ filterStats.totalFetched }} 个商品</span>
            <span class="divider">|</span>
            <span>符合条件: {{ filterStats.filteredCount }} 个商品</span>
            <span class="divider">|</span>
            <span class="hidden-count">已过滤: {{ filterStats.hiddenCount }} 个商品</span>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div slot="footer" class="dialog-footer">
      <div class="selected-info">
        <span v-if="selectedProducts.length > 0">
          已选择 {{ selectedProducts.length }} 个商品
        </span>
      </div>
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="selectedProducts.length === 0">
          确定选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getShoopStoreList, categoryList } from '../../../libs/api'

export default {
  name: 'ProductSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 是否多选：默认单选，传入 true 开启多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 多选时的上限（可选）
    maxSelected: {
      type: Number,
      default: Infinity
    },
    // 商品类型过滤：'miaosha' 只显示秒杀商品，'group' 只显示非秒杀且非限购商品
    productType: {
      type: String,
      default: 'all',
      validator: value => ['all', 'miaosha', 'group'].includes(value)
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      productList: [],
      selectedProducts: [],
      searchForm: {
        name: '',
        category_id: '',
        status: ''
      },
      categoryOptions: [],
      pagination: {
        current: 1,
        size: 20,
        total: 0
      },
      searchTimer: null,
      // 过滤统计信息
      filterStats: {
        totalFetched: 0,  // 从后端获取的总数
        filteredCount: 0, // 过滤后的数量
        hiddenCount: 0    // 隐藏的数量
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.getProductList()
        this.getCategoryOptions()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    // 获取商品列表
    getProductList() {
      this.loading = true
      const params = {
        ...this.searchForm,
        page: this.pagination.current,
        limit: this.pagination.size
      }
      
      // 根据商品类型添加过滤条件
      if (this.productType === 'miaosha') {
        // 只显示秒杀商品
        params.is_goods = 1
      } else if (this.productType === 'group') {
        // 只显示非秒杀且非限购商品
        params.is_goods = 0
        params.limit_quantity = 0
      }
      
      getShoopStoreList(params).then(res => {
        if (res && res.data) {
          let products = res.data.data || []
          const originalCount = products.length
          
          // 如果后端没有完全过滤，在前端再次过滤
          if (this.productType === 'miaosha') {
            products = products.filter(product => product.is_goods === 1)
          } else if (this.productType === 'group') {
            products = products.filter(product => product.is_goods === 0 && (!product.limit_quantity || product.limit_quantity === 0))
          }
          
          // 更新过滤统计信息
          this.filterStats.totalFetched = originalCount
          this.filterStats.filteredCount = products.length
          this.filterStats.hiddenCount = originalCount - products.length
          
          this.productList = products
          this.pagination.total = res.data.total || 0
        } else {
          this.productList = []
          this.pagination.total = 0
          this.filterStats = {
            totalFetched: 0,
            filteredCount: 0,
            hiddenCount: 0
          }
        }
        this.loading = false
      }).catch(() => {
        this.productList = []
        this.pagination.total = 0
        this.filterStats = {
          totalFetched: 0,
          filteredCount: 0,
          hiddenCount: 0
        }
        this.loading = false
      })
    },
    
    // 获取分类选项
    getCategoryOptions() {
      categoryList().then(res => {
        if (res && res.code === 1 && res.data) {
          this.categoryOptions = this.flattenCategories(res.data)
        } else {
          this.categoryOptions = []
        }
      }).catch(() => {
        this.categoryOptions = []
      })
    },
    // 将分类树展平为列表
    flattenCategories(categories) {
      const allCategories = []
      const flatten = (cats) => {
        cats.forEach((category) => {
          allCategories.push({
            id: category.id,
            name: category.name,
            level: category.level,
            parent_id: category.parent_id
          })
          if (category.children && category.children.length > 0) {
            flatten(category.children)
          }
        })
      }
      flatten(categories)
      return allCategories
    },
    
    // 搜索
    handleSearch() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      // 设置防抖，300ms 后执行搜索
      this.searchTimer = setTimeout(() => {
        this.pagination.current = 1
        this.getProductList()
      }, 300)
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        category_id: '',
        status: ''
      }
      this.pagination.current = 1
      this.getProductList()
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.size = val
      this.pagination.current = 1
      this.getProductList()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getProductList()
    },
    
    // 选择改变
    handleSelectionChange(selection) {
      // 防止在加载过程中处理选择
      if (this.loading) {
        return
      }
      
      if (!this.multiple) {
        // 单选：仅保留最后一次选择的那一项
        if (selection.length > 1) {
          // 如果选择了多个，只保留最后一个
          const last = selection[selection.length - 1]
          this.$refs.productTable.clearSelection()
          this.$nextTick(() => {
            this.$refs.productTable.toggleRowSelection(last, true)
            this.selectedProducts = [last]
          })
        } else {
          this.selectedProducts = selection
        }
        return
      }
      // 多选：尊重上限
      if (selection.length > this.maxSelected) {
        this.$message.warning(`最多可选择 ${this.maxSelected} 个商品`)
        // 还原为前 maxSelected 个
        const kept = selection.slice(0, this.maxSelected)
        this.$refs.productTable.clearSelection()
        this.$nextTick(() => {
          kept.forEach(row => this.$refs.productTable.toggleRowSelection(row, true))
          this.selectedProducts = kept
        })
        return
      }
      this.selectedProducts = selection
    },
    
    // 获取分类名称
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.id === categoryId)
      return category ? category.name : '未知分类'
    },
    
    // 确认选择
    handleConfirm() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请选择商品')
        return
      }
      if (this.multiple) {
        const result = this.selectedProducts.map(p => ({
          id: p.id,
          name: p.name,
          main_image: p.main_image,
          price: p.sku ? p.sku.price : 0
        }))
        this.$emit('confirm', result)
      } else {
        const p = this.selectedProducts[0]
        this.$emit('confirm', {
          id: p.id,
          name: p.name,
          main_image: p.main_image,
          price: p.sku ? p.sku.price : 0
        })
      }
      this.handleClose()
    },
    
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.selectedProducts = []
      this.$refs.productTable.clearSelection()
    }
  },
  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  }
}
</script>

<style scoped>
.product-selector-dialog .el-dialog__body {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.product-info {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.price-info {
  display: flex;
  flex-direction: column;
  font-size: 12px;
}

.current-price {
  color: #e6a23c;
  font-weight: bold;
  font-size: 14px;
}

.vip-price {
  color: #f56c6c;
}

.market-price {
  color: #909399;
  text-decoration: line-through;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.filter-stats {
  margin: 15px 0;
}

.stats-detail {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}

.divider {
  color: #dcdfe6;
  font-weight: normal;
}

.hidden-count {
  color: #e6a23c;
  font-weight: 500;
}
</style>
